{% extends "base.html" %}

{% block title %}上传学习资源 - 校园生活助手{% endblock %}

{% block css %}
<style>
    .upload-container {
        background-color: white;
        border-radius: 0.5rem;
        padding: 2rem;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        max-width: 800px;
        margin: 0 auto;
    }
    .upload-header {
        text-align: center;
        margin-bottom: 2rem;
    }
    .upload-icon {
        font-size: 4rem;
        color: #007bff;
        margin-bottom: 1rem;
    }
    .upload-title {
        font-size: 1.5rem;
        font-weight: 600;
        color: #495057;
    }
    .upload-subtitle {
        color: #6c757d;
        margin-top: 0.5rem;
    }
    .form-group {
        margin-bottom: 1.5rem;
    }
    .form-label {
        font-weight: 600;
        color: #495057;
        margin-bottom: 0.5rem;
        display: block;
    }
    .form-control {
        width: 100%;
        padding: 0.75rem;
        border: 1px solid #dee2e6;
        border-radius: 0.25rem;
        font-size: 1rem;
        transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
    }
    .form-control:focus {
        border-color: #007bff;
        outline: 0;
        box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
    }
    .form-text {
        color: #6c757d;
        font-size: 0.875rem;
        margin-top: 0.25rem;
    }
    .file-upload-area {
        border: 2px dashed #dee2e6;
        border-radius: 0.5rem;
        padding: 2rem;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s ease;
        background-color: #f8f9fa;
    }
    .file-upload-area:hover {
        border-color: #007bff;
        background-color: #e9ecef;
    }
    .file-upload-icon {
        font-size: 2.5rem;
        color: #6c757d;
        margin-bottom: 1rem;
    }
    .file-upload-text {
        color: #6c757d;
        margin-bottom: 0.5rem;
    }
    .file-upload-hint {
        color: #adb5bd;
        font-size: 0.875rem;
    }
    .file-upload-input {
        display: none;
    }
    .file-preview {
        margin-top: 1.5rem;
        padding: 1rem;
        background-color: #f8f9fa;
        border-radius: 0.25rem;
        display: none;
    }
    .file-preview.show {
        display: block;
    }
    .file-preview-header {
        display: flex;
        align-items: center;
        margin-bottom: 0.5rem;
    }
    .file-preview-icon {
        font-size: 1.5rem;
        color: #007bff;
        margin-right: 0.75rem;
    }
    .file-preview-name {
        font-weight: 600;
        color: #495057;
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    .file-preview-size {
        color: #6c757d;
        font-size: 0.875rem;
        margin-right: 1rem;
    }
    .file-preview-remove {
        color: #dc3545;
        cursor: pointer;
        font-size: 1.25rem;
        transition: color 0.2s;
    }
    .file-preview-remove:hover {
        color: #c82333;
    }
    .form-actions {
        display: flex;
        justify-content: flex-end;
        gap: 1rem;
        margin-top: 2rem;
        padding-top: 1.5rem;
        border-top: 1px solid #e9ecef;
    }
    .btn {
        padding: 0.75rem 1.5rem;
        border-radius: 0.25rem;
        font-size: 1rem;
        font-weight: 600;
        transition: all 0.2s;
        cursor: pointer;
        border: none;
    }
    .btn-primary {
        background-color: #007bff;
        color: white;
    }
    .btn-primary:hover {
        background-color: #0056b3;
    }
    .btn-primary:disabled {
        background-color: #6c757d;
        cursor: not-allowed;
    }
    .btn-secondary {
        background-color: #6c757d;
        color: white;
    }
    .btn-secondary:hover {
        background-color: #545b62;
    }
    .form-check {
        display: flex;
        align-items: center;
        margin-bottom: 0.5rem;
    }
    .form-check-input {
        margin-right: 0.5rem;
    }
    .form-check-label {
        color: #495057;
        margin-bottom: 0;
    }
    .tag-input-container {
        border: 1px solid #dee2e6;
        border-radius: 0.25rem;
        padding: 0.5rem;
        min-height: 44px;
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
        align-items: center;
    }
    .tag-input {
        border: none;
        flex: 1;
        min-width: 150px;
        outline: none;
        font-size: 0.875rem;
    }
    .tag {
        display: flex;
        align-items: center;
        background-color: #e9ecef;
        color: #495057;
        padding: 0.25rem 0.5rem;
        border-radius: 1rem;
        font-size: 0.875rem;
    }
    .tag-remove {
        margin-left: 0.5rem;
        cursor: pointer;
        color: #6c757d;
        transition: color 0.2s;
    }
    .tag-remove:hover {
        color: #495057;
    }
    .form-row {
        display: flex;
        gap: 1rem;
        margin-bottom: 1.5rem;
    }
    .form-col {
        flex: 1;
    }
    .alert {
        padding: 1rem;
        border-radius: 0.25rem;
        margin-bottom: 1.5rem;
    }
    .alert-success {
        background-color: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
    }
    .alert-danger {
        background-color: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
    }
    .alert-warning {
        background-color: #fff3cd;
        color: #856404;
        border: 1px solid #ffeaa7;
    }
    .alert-info {
        background-color: #d1ecf1;
        color: #0c5460;
        border: 1px solid #bee5eb;
    }
</style>
{% endblock %}

{% block content %}
<div class="mb-6">
    <h1 class="text-2xl font-bold text-gray-800">
        <i class="fa fa-upload mr-2 text-primary"></i>上传学习资源
    </h1>
    <p class="text-gray-600">与大家分享优质学习资料，助力学业成长</p>
</div>

<!-- 消息提示区域 -->
{% with messages = get_flashed_messages(with_categories=true) %}
    {% if messages %}
        {% for category, message in messages %}
            <div class="alert alert-{{ category }} fade-in mb-4" role="alert">
                <button type="button" class="close" data-bs-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                {{ message }}
            </div>
        {% endfor %}
    {% endif %}
{% endwith %}

<div class="upload-container">
    <div class="upload-header">
        <div class="upload-icon">
            <i class="fa fa-cloud-upload"></i>
        </div>
        <h2 class="upload-title">上传新资源</h2>
        <p class="upload-subtitle">填写资源信息并上传文件，与其他同学共享学习资料</p>
    </div>
    
    <form id="upload-form" method="POST" enctype="multipart/form-data">
        <!-- 资源标题 -->
        <div class="form-group">
            <label for="resource-title" class="form-label">资源标题 <span class="text-danger">*</span></label>
            <input type="text" id="resource-title" name="title" class="form-control" placeholder="请输入资源标题" required>
            <small class="form-text">请为您的资源提供一个清晰、描述性的标题</small>
        </div>
        
        <!-- 资源描述 -->
        <div class="form-group">
            <label for="resource-description" class="form-label">资源描述 <span class="text-danger">*</span></label>
            <textarea id="resource-description" name="description" class="form-control" rows="5" placeholder="请详细描述您的资源内容、用途等信息" required></textarea>
            <small class="form-text">详细的描述有助于其他同学更好地了解您分享的资源</small>
        </div>
        
        <!-- 文件上传区域 -->
        <div class="form-group">
            <label class="form-label">上传文件 <span class="text-danger">*</span></label>
            <div class="file-upload-area" id="file-upload-area">
                <input type="file" id="file-upload-input" name="file" class="file-upload-input" required>
                <div class="file-upload-icon">
                    <i class="fa fa-file-o"></i>
                </div>
                <div class="file-upload-text">点击或拖拽文件到此处上传</div>
                <div class="file-upload-hint">支持格式：PDF、Word、Excel、PPT、视频、音频、代码文件等，最大50MB</div>
            </div>
            
            <!-- 文件预览 -->
            <div id="file-preview" class="file-preview">
                <div class="file-preview-header">
                    <div class="file-preview-icon">
                        <i class="fa fa-file-o"></i>
                    </div>
                    <div class="file-preview-name" id="file-preview-name"></div>
                    <div class="file-preview-size" id="file-preview-size"></div>
                    <div class="file-preview-remove" id="file-preview-remove">
                        <i class="fa fa-times"></i>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 资源类型和学科分类 -->
        <div class="form-row">
            <div class="form-col">
                <div class="form-group">
                    <label for="resource-type" class="form-label">资源类型 <span class="text-danger">*</span></label>
                    <select id="resource-type" name="type" class="form-control" required>
                        <option value="">请选择资源类型</option>
                        <option value="ppt">PPT课件</option>
                        <option value="pdf">PDF文档</option>
                        <option value="doc">Word文档</option>
                        <option value="excel">Excel表格</option>
                        <option value="video">视频教程</option>
                        <option value="audio">音频资源</option>
                        <option value="code">代码文件</option>
                        <option value="other">其他资源</option>
                    </select>
                </div>
            </div>
            <div class="form-col">
                <div class="form-group">
                    <label for="resource-subject" class="form-label">学科分类 <span class="text-danger">*</span></label>
                    <select id="resource-subject" name="subject" class="form-control" required>
                        <option value="">请选择学科分类</option>
                        <option value="计算机科学">计算机科学</option>
                        <option value="数学">数学</option>
                        <option value="物理">物理</option>
                        <option value="化学">化学</option>
                        <option value="生物">生物</option>
                        <option value="英语">英语</option>
                        <option value="经济学">经济学</option>
                        <option value="管理学">管理学</option>
                        <option value="文学">文学</option>
                        <option value="历史学">历史学</option>
                        <option value="哲学">哲学</option>
                        <option value="其他">其他</option>
                    </select>
                </div>
            </div>
        </div>
        
        <!-- 适用年级和关联课程 -->
        <div class="form-row">
            <div class="form-col">
                <div class="form-group">
                    <label for="resource-grade" class="form-label">适用年级</label>
                    <select id="resource-grade" name="grade" class="form-control">
                        <option value="">请选择适用年级（选填）</option>
                        <option value="大一">大一</option>
                        <option value="大二">大二</option>
                        <option value="大三">大三</option>
                        <option value="大四">大四</option>
                        <option value="研究生">研究生</option>
                        <option value="全年级">全年级</option>
                    </select>
                </div>
            </div>
            <div class="form-col">
                <div class="form-group">
                    <label for="resource-course" class="form-label">关联课程</label>
                    <select id="resource-course" name="related_course" class="form-control">
                        <option value="">请选择关联课程（选填）</option>
                        {% for course in user_courses %}
                            <option value="{{ course.id }}">{{ course.name }}</option>
                        {% endfor %}
                    </select>
                </div>
            </div>
        </div>
        
        <!-- 资源标签 -->
        <div class="form-group">
            <label for="resource-tags" class="form-label">资源标签</label>
            <div class="tag-input-container" id="tag-input-container">
                <input type="text" id="tag-input" class="tag-input" placeholder="输入标签后按回车添加" data-max-tags="5">
            </div>
            <input type="hidden" id="resource-tags" name="tags">
            <small class="form-text">最多添加5个标签，用空格分隔的关键词将被视为多个标签</small>
        </div>
        
        <!-- 资源设置 -->
        <div class="form-group">
            <h3 class="form-label">资源设置</h3>
            
            <div class="form-check">
                <input type="checkbox" id="allow-comments" name="allow_comments" class="form-check-input" checked>
                <label for="allow-comments" class="form-check-label">允许其他用户评论</label>
            </div>
            
            <div class="form-check">
                <input type="checkbox" id="require-login" name="require_login" class="form-check-input">
                <label for="require-login" class="form-check-label">仅登录用户可下载</label>
            </div>
            
            <div class="form-check">
                <input type="checkbox" id="notify-me" name="notify_me" class="form-check-input" checked>
                <label for="notify-me" class="form-check-label">当有人下载或评论时通知我</label>
            </div>
        </div>
        
        <!-- 表单操作按钮 -->
        <div class="form-actions">
            <button type="button" class="btn btn-secondary" onclick="window.history.back()">取消</button>
            <button type="submit" class="btn btn-primary" id="submit-button">
                <i class="fa fa-check mr-2"></i>提交上传
            </button>
        </div>
    </form>
</div>
{% endblock %}

{% block js %}
<script>
    // 文件上传区域交互
    const fileUploadArea = document.getElementById('file-upload-area');
    const fileUploadInput = document.getElementById('file-upload-input');
    const filePreview = document.getElementById('file-preview');
    const filePreviewName = document.getElementById('file-preview-name');
    const filePreviewSize = document.getElementById('file-preview-size');
    const filePreviewRemove = document.getElementById('file-preview-remove');
    const submitButton = document.getElementById('submit-button');
    
    // 点击上传区域触发文件选择
    fileUploadArea.addEventListener('click', function() {
        fileUploadInput.click();
    });
    
    // 拖拽文件到上传区域
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        fileUploadArea.addEventListener(eventName, preventDefaults, false);
    });
    
    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }
    
    ['dragenter', 'dragover'].forEach(eventName => {
        fileUploadArea.addEventListener(eventName, highlight, false);
    });
    
    ['dragleave', 'drop'].forEach(eventName => {
        fileUploadArea.addEventListener(eventName, unhighlight, false);
    });
    
    function highlight() {
        fileUploadArea.style.borderColor = '#007bff';
        fileUploadArea.style.backgroundColor = '#e9ecef';
    }
    
    function unhighlight() {
        fileUploadArea.style.borderColor = '#dee2e6';
        fileUploadArea.style.backgroundColor = '#f8f9fa';
    }
    
    // 处理文件拖放
    fileUploadArea.addEventListener('drop', handleDrop, false);
    
    function handleDrop(e) {
        const dt = e.dataTransfer;
        const files = dt.files;
        
        if (files.length > 0) {
            handleFiles(files[0]);
        }
    }
    
    // 处理文件选择
    fileUploadInput.addEventListener('change', function() {
        if (this.files.length > 0) {
            handleFiles(this.files[0]);
        }
    });
    
    // 处理文件预览
    function handleFiles(file) {
        // 检查文件大小（50MB）
        const maxSize = 50 * 1024 * 1024;
        if (file.size > maxSize) {
            alert('文件大小不能超过50MB');
            fileUploadInput.value = '';
            return;
        }
        
        // 显示文件预览
        filePreviewName.textContent = file.name;
        filePreviewSize.textContent = formatFileSize(file.size);
        filePreview.classList.add('show');
        
        // 更新文件图标
        updateFileIcon(file.name);
    }
    
    // 格式化文件大小
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
    
    // 更新文件图标
    function updateFileIcon(filename) {
        const extension = filename.split('.').pop().toLowerCase();
        const fileIcon = filePreview.querySelector('.file-preview-icon i');
        
        // 移除所有fa-file-*类
        fileIcon.className = 'fa';
        
        // 根据文件扩展名设置图标
        if (['doc', 'docx'].includes(extension)) {
            fileIcon.classList.add('fa-file-word-o');
        } else if (['xls', 'xlsx'].includes(extension)) {
            fileIcon.classList.add('fa-file-excel-o');
        } else if (['ppt', 'pptx'].includes(extension)) {
            fileIcon.classList.add('fa-file-powerpoint-o');
        } else if (['pdf'].includes(extension)) {
            fileIcon.classList.add('fa-file-pdf-o');
        } else if (['jpg', 'jpeg', 'png', 'gif'].includes(extension)) {
            fileIcon.classList.add('fa-file-image-o');
        } else if (['mp4', 'avi', 'mov', 'wmv'].includes(extension)) {
            fileIcon.classList.add('fa-file-video-o');
        } else if (['mp3', 'wav', 'flac'].includes(extension)) {
            fileIcon.classList.add('fa-file-audio-o');
        } else if (['zip', 'rar', '7z', 'tar'].includes(extension)) {
            fileIcon.classList.add('fa-file-archive-o');
        } else if (['html', 'css', 'js', 'py', 'java', 'cpp', 'c', 'php', 'rb', 'go'].includes(extension)) {
            fileIcon.classList.add('fa-file-code-o');
        } else {
            fileIcon.classList.add('fa-file-o');
        }
    }
    
    // 移除文件
    filePreviewRemove.addEventListener('click', function() {
        fileUploadInput.value = '';
        filePreview.classList.remove('show');
    });
    
    // 标签输入功能
    const tagInputContainer = document.getElementById('tag-input-container');
    const tagInput = document.getElementById('tag-input');
    const resourceTags = document.getElementById('resource-tags');
    let tags = [];
    
    // 监听标签输入框的回车事件
    tagInput.addEventListener('keydown', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            addTag(this.value.trim());
            this.value = '';
        }
        
        // 当输入框为空且按下退格键时，删除最后一个标签
        if (e.key === 'Backspace' && this.value.trim() === '' && tags.length > 0) {
            removeTag(tags.length - 1);
        }
    });
    
    // 添加标签
    function addTag(tagText) {
        if (!tagText || tags.length >= 5) {
            return;
        }
        
        // 分割空格分隔的多个标签
        const newTags = tagText.split(/\s+/).filter(t => t && !tags.includes(t));
        
        newTags.forEach(tag => {
            if (tags.length < 5) {
                tags.push(tag);
                renderTags();
            }
        });
    }
    
    // 移除标签
    function removeTag(index) {
        tags.splice(index, 1);
        renderTags();
    }
    
    // 渲染标签
    function renderTags() {
        // 清空标签容器（除了输入框）
        while (tagInputContainer.firstChild) {
            if (tagInputContainer.firstChild === tagInput) {
                break;
            }
            tagInputContainer.removeChild(tagInputContainer.firstChild);
        }
        
        // 添加标签
        tags.forEach((tag, index) => {
            const tagElement = document.createElement('div');
            tagElement.className = 'tag';
            tagElement.innerHTML = `
                <span>${tag}</span>
                <span class="tag-remove" data-index="${index}"><i class="fa fa-times"></i></span>
            `;
            
            // 将标签添加到输入框前面
            tagInputContainer.insertBefore(tagElement, tagInput);
        });
        
        // 更新隐藏输入框的值
        resourceTags.value = tags.join(',');
        
        // 为新添加的标签移除按钮添加事件监听
        document.querySelectorAll('.tag-remove').forEach(button => {
            button.addEventListener('click', function() {
                const index = parseInt(this.getAttribute('data-index'));
                removeTag(index);
            });
        });
    }
    
    // 表单提交处理
    const uploadForm = document.getElementById('upload-form');
    
    uploadForm.addEventListener('submit', function(e) {
        // 验证必填字段
        const title = document.getElementById('resource-title').value.trim();
        const description = document.getElementById('resource-description').value.trim();
        const file = fileUploadInput.files.length > 0;
        const type = document.getElementById('resource-type').value;
        const subject = document.getElementById('resource-subject').value;
        
        if (!title || !description || !file || !type || !subject) {
            e.preventDefault();
            alert('请填写所有必填字段并上传文件');
            return;
        }
        
        // 显示加载状态
        submitButton.disabled = true;
        submitButton.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i>上传中...';
        
        // 这里不阻止表单提交，让它继续进行
    });
    
    // 页面载入动画
    document.addEventListener('DOMContentLoaded', function() {
        const uploadContainer = document.querySelector('.upload-container');
        
        uploadContainer.style.opacity = '0';
        uploadContainer.style.transform = 'translateY(20px)';
        uploadContainer.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
        
        setTimeout(() => {
            uploadContainer.style.opacity = '1';
            uploadContainer.style.transform = 'translateY(0)';
        }, 100);
    });
</script>
{% endblock %}